﻿
using System.Collections.Generic;

using Irony.Compiler;

namespace IronLua.Ast {

	public class AssignStatement : Statement {

		readonly ExpressionList left = new ExpressionList ();
		readonly ExpressionList right = new ExpressionList ();

		public ExpressionList Left {
			get { return left; }
		}

		public ExpressionList Right {
			get { return right; }
		}

		public override LuaNodeType NodeType {
			get { return LuaNodeType.AssignStatement; }
		}

		public AssignStatement (CompilerContext context, NonTerminal nonTerminal, SourceLocation location, AstNodeList childNodes)
			: base (context, nonTerminal, location, childNodes)
		{
			left.AddRange (CollectLeftExpressions ());
			right.AddRange (CollectRightExpressions ());
		}

		IEnumerable<Expression> CollectLeftExpressions ()
		{
			var list = ChildNodes [0];
			yield return list.ChildNodes [0].ToExpression ();

			if (list.ChildNodes.Count > 1 && list.ChildNodes [1] != null && list.ChildNodes [1].ChildNodes.Count > 0) {
				foreach (var node in list.ChildNodes [1].ChildNodes) {
					yield return node.ChildNodes [0].ToExpression ();
				}
			}
		}

		IEnumerable<Expression> CollectRightExpressions ()
		{
			var list = ChildNodes [2];
			foreach (var node in list.ChildNodes [0].ChildNodes)
				yield return node.ChildNodes [0].ToExpression ();

			if (list.ChildNodes.Count > 1 && list.ChildNodes [1] != null)
				yield return list.ChildNodes [1].ToExpression ();
		}

		public override void Accept (ILuaAstVisitor visitor)
		{
			visitor.VisitAssignStatement (this);
		}
	}
}
